const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const multiparty = require("multiparty");
const fse = require("fs-extra");
const mergeFileChunk = require("./mergeFile.js");

const app = express();
// parse application/x-www-form-urlencoded
// app.use(bodyParser.urlencoded({ extended: false }));
// // parse application/json
// app.use(bodyParser.json());

const UPLOAD_DIR = path.resolve(__dirname, ".", "target");
let step = 0;

// 定义一个休眠方法
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

app.get("/", (req, res) => {
  res.header("Content-Type", "text/html;charset=utf-8");
  res.sendFile(path.resolve(__dirname, "./index.html"));
});

app.post("/merge", async (req, res) => {
  const perSize = req.query.perSize;
  const fileName = req.query.filename;
  const filePath = path.resolve(UPLOAD_DIR, ".", fileName);
  await mergeFileChunk(res, fileName.split(".")[0], filePath, perSize);
  return;
});

app.post("/chunk", async (req, res) => {
  step++;
  const myMultiparty = new multiparty.Form();
  myMultiparty.parse(req, async (err, fields, files) => {
    if (err) return;
    const [fileName] = fields.fileName;
    const [chunk] = files.chunk;

    const slice_dir_name = fileName.split("-")[0];
    const chunkDirPath = path.resolve(UPLOAD_DIR, ".", slice_dir_name);

    if (!fse.existsSync(chunkDirPath)) {
      await fse.mkdirs(chunkDirPath);
    }

    await fse.move(chunk.path, `${chunkDirPath}/${fileName}`, {
      overwrite: true,
    });
    console.log(step);
    // await sleep(1000 * fileName.split('-')[1]);
    // console.log(1000 * fileName.split("-")[1]);
    res.send("/ ok");
  });
});

app.listen(5000);
